package com.wolf.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wolf.common.constant.AuthServerConstant;
import com.wolf.common.utils.HttpUtils;
import com.wolf.common.utils.R;
import com.wolf.gulimall.auth.feign.MemberFeignService;
import com.wolf.common.vo.MemberEntityVo;
import com.wolf.gulimall.auth.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Slf4j
@Controller
public class Oauth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id","1cfabafef58a73e20f512a6553533a46d584fdab41751446fcb1cb8f1fa902a2");
        map.put("client_secret","90b8a2db42bb29fc51c4a18d0f0e8298d46c38ff43fff5dea200a5e4a66a2087");
        map.put("code",code);
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimallwolf.com/oauth2.0/gitee/success");
        //根据code,拿到access_token,即操作gitee信息的令牌
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), null, map);
        //处理返回信息
        if(response.getStatusLine().getStatusCode()==200){
            log.info("获取access_token访问令牌成功!!");
            //成功获取到access_token
            String s = EntityUtils.toString(response.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(s, SocialUserVo.class);
            //如果用户第一次进入网站,自动注册一个会员账号,即为当前社交登录用户新增一个会员账号信息
            R login = memberFeignService.login(socialUserVo);
            if(login.getCode()==0){
                //登录成功返回登录首页
                MemberEntityVo memberEntityVo = login.getData("data",new TypeReference<MemberEntityVo>(){});
                log.info("登录成功：用户信息：{}",memberEntityVo.toString());
                //将用户信息放入session 存储到redis中,再次访问的时候去redis中拿到这个session,避免重复登录
                //存在问题 :这个session的作用域只在当前子域名下,其他子域名进行访问的时候拿不到这个session
                //提高这个session的作用域 即解决子域session共享问题

                httpSession.setAttribute(AuthServerConstant.LOGIN_USER,memberEntityVo);
                return "redirect:http://gulimallwolf.com";
            }else{
                return "redirect:http://auth.gulimallwolf.com/login.html";
            }
        }else{
            return "redirect:http://auth.gulimallwolf.com/login.html";
        }


    }
}
